package com.kgdev.cweb.mbean.global.session;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Locale;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import com.kgdev.cweb.beans.prod.impl.ClientBean;
import com.kgdev.cweb.entities.prod.managed.Client;
import com.kgdev.cweb.mbean.global.application.ResourceBundleControl;
import com.kgdev.cweb.resmng.config.ConfigPropetyManager;
import com.kgdev.cweb.resmng.i18n.MYSQLShortTextResourceBundle;
import com.kgdev.cweb.resmng.i18n.MYSQLTextResourceBundle;

@ManagedBean
@SessionScoped
public class LocalisationBean implements Serializable {

	@ManagedProperty(value = "#{loginBean}")
	LoginBean loginBean;


	public void setLoginBean(LoginBean loginBean) {
		this.loginBean = loginBean;
	}

	@EJB
	ClientBean clientBean;

	@ManagedProperty(value = "#{resourceBundleControl}")
	ResourceBundleControl resourceBundleControl;

	public void setResourceBundleControl(
			ResourceBundleControl resourceBundleControl) {
		this.resourceBundleControl = resourceBundleControl;
	}

	private Locale currentLocale;

	private static final long serialVersionUID = 1L;

	private HashMap<String, Locale> locales = new HashMap<>();

	public Locale getCurrentLocale() {
		return currentLocale;
	}

	public String getShortText(String pKey) {
		return MYSQLShortTextResourceBundle.getBundle(
				ResourceBundleControl.SHORT_TEXT_BUNDLE, currentLocale,
				resourceBundleControl).getString(pKey);
	}

	public String getText(String pKey) {
		return MYSQLTextResourceBundle.getBundle(
				ResourceBundleControl.TEXT_BUNDLE, currentLocale,
				resourceBundleControl).getString(pKey);
	}

	public void setCurrentLocale(Locale currentLocale) {
		this.currentLocale = currentLocale;
	}

	public String switchLocale(String pLanCode) {
		setCurrentLocale(retrieveLocale(pLanCode));
		Client currentClient = loginBean.getAutenticatedClient();
		if (currentClient != null) {
			currentClient.setDefaultLanguage(pLanCode);
			clientBean.edit(currentClient);
		}
		return "toStoreHome";
	}

	@PostConstruct
	public void init() {
		setDefaultLocale();
	}

	public void setUserLocale() {
		if (loginBean.getAutenticatedClient() != null) {
			setCurrentLocale(retrieveLocale(loginBean.getAutenticatedClient()
					.getDefaultLanguage()));
		}
	}

	public void setDefaultLocale() {
		ConfigPropetyManager configPropetyManager = new ConfigPropetyManager();
		setCurrentLocale(retrieveLocale(configPropetyManager
				.getString("defaultLocale")));
	}

	private Locale retrieveLocale(String pLanCode) {
		Locale locale = null;
		if (!locales.containsKey(pLanCode)) {
			locale = new Locale(pLanCode);
			locales.put(pLanCode, locale);
		} else {
			locale = locales.get(pLanCode);
		}
		return locale;
	}

}
